<?php

namespace App\Http\Controllers\Admin\HomeUsers\Api;

use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Http\Controllers\Controller;
use App\Model\HomeUsers;

class homeUsersApi extends Controller
{
    /**
	 * 查询一个表的某些字段,并且分页
	 * @param  [str] $tab  [表名]
	 * @param  [array] $tit  [字段]
	 * @param  [int] $page [分页显示数]
	 * @return [array]       [返回数据]
	 */
	public function page($tab, $tit, $page)
	{

		$users = DB::table($tab)->select($tit)->simplePaginate($page);

		return $users;

	}

	public function add($arr)
	{
		$pwd = Hash::make($_POST['password']);
		$res = DB::table('home_users')->insert([
                'nickname' => $arr['nickname'],
                'username' => $arr['username'],
                'password' => $pwd,
                'sex' => $arr['sex'],
                'address' => $arr['address'],
                'code' => $arr['code'],
                'user_level_id' => $arr['level'],
                'phone' => $arr['phone'],
                'email' => $arr['email'],
                'user_score' => 0,
                'state' => 1,
                'sign_time' => date('Y-m-d H:i:s'),
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

		if($res){
			echo 1;
		} else {
			echo 2;
		}
	}

	/**
	 * [用id找值]
	 * @param  [str] $tab [需要查找的表]
	 * @param  [int] $id  [需要查找的表\id]
	 * @return [arr]      [这个id的数据]
	 */
	public function find($tab, $id)
	{

		$res = DB::select('select * from '.$tab.' where id = :id', ['id' => $id]);

		return $res;
	}

	//修改密码
	public function doChagePassword(Request $request)
	{
		// $a = 'aaa';

		$pwd = Hash::make($_POST['newpassword']);
		$res = DB::update('update home_users set password = ? where id = ?', [$pwd, $_POST['id']]);

		if ($res) {
			echo 1;
		} else {
			echo 2;
		}
	}

	//进行修改
	public function doedit(Request $request)
	{
		// dd($request->username);

		// $res = HomeUsers::where('id',$request['id'])->get()->toArray();
		// dd($request->toArray());

		$chg = $request->toArray();
		$res = HomeUsers::find(1)->where('id', $chg['id'])->first();

		

		$res->nickname = $chg['nickname'];
		$res->sex = $chg['sex'];
		$res->address = $chg['address'];
		$res->code = $chg['code'];
		$res->phone = $chg['phone'];
		$res->email = $chg['email'];
		$res->user_level_id = $chg['level'];


		$res->save();

		echo 1;


	}

	public function start()
	{
		$res = DB::update('update home_users set state = 1 where id = ?', [$_GET['id']]);
		if($res){
			echo 1;
		}
	}

	public function stop()
	{
		$res = DB::update('update home_users set state = 0 where id = ?', [$_GET['id']]);
		if($res){
			echo 1;
		}
	}
}
